﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace EcoSystem
{
    public class SystemMenuAppService : CrudAppService<
        SystemMenu,
        SystemMenuDto,
        Guid,
        GetSystemMenuInput,
        CreateOrUpdateSystemMenuDto,
        CreateOrUpdateSystemMenuDto>, ISystemMenuAppService
    {
        public SystemMenuAppService(IRepository<SystemMenu, Guid> repository) : base(repository)
        {

        }

        public override async Task<PagedResultDto<SystemMenuDto>> GetListAsync(GetSystemMenuInput input)
        {
            var query = (await Repository.GetQueryableAsync()).AsNoTracking()
                .WhereIf(!input.GroupName.IsNullOrWhiteSpace(), x => x.GroupName.Equals(input.GroupName))
                .WhereIf(!input.Name.IsNullOrWhiteSpace(), x => x.DisplayName.Contains(input.Name) || x.GroupName.Contains(input.Name) || x.Remarks.Contains(input.Name))
                .WhereIf(input.Status.HasValue, x => x.Status == input.Status)
                .WhereIf(input.ParentId.HasValue, x => x.ParentId == input.ParentId);
            var total = await query.CountAsync();
            var items = await query.OrderBy(x => x.Id).PageBy(input).ToListAsync();
            return new PagedResultDto<SystemMenuDto>()
            {
                Items = await MapToGetListOutputDtosAsync(items),
                TotalCount = total
            };
        }

        public async Task<List<SystemMenuDto>> GetAllListAsync(GetSystemMenuInput input)
        {
            var query = (await Repository.GetQueryableAsync()).AsNoTracking()
                .WhereIf(!input.GroupName.IsNullOrWhiteSpace(), x => x.GroupName.Equals(input.GroupName))
                .WhereIf(!input.Name.IsNullOrWhiteSpace(), x => x.DisplayName.Contains(input.Name) || x.GroupName.Contains(input.Name) || x.Remarks.Contains(input.Name))
                .WhereIf(input.Status.HasValue, x => x.Status == input.Status)
                .WhereIf(input.ParentId.HasValue, x => x.ParentId == input.ParentId);
            var items = await query.OrderBy(x => x.ParentId).ThenBy(x => x.SortIndex).ThenByDescending(x => x.Id).ToListAsync();
            return await MapToGetListOutputDtosAsync(items);
        }
    }
}
